package com.freesky.biz.rights.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.freesky.biz.rights.domain.EncryptBatchEntity;
import com.freesky.biz.rights.pojo.EncryptCodePo;
import com.freesky.biz.rights.service.IEncryptBatchService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.annotation.Log;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import com.freesky.common.core.domain.entity.SysUser;
import com.freesky.common.core.page.TableDataInfo;
import com.freesky.common.enums.BusinessType;
import com.freesky.common.exception.base.BaseException;
import com.freesky.common.utils.HashIdUtils;
import com.freesky.common.utils.SecurityUtils;
import com.freesky.common.utils.StringUtils;
import com.freesky.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 券码批次管理
 */
@RestController
@RequestMapping("/rights/encrypt/batch")
public class EncryptBatchController extends BaseController {

    @Autowired
    private IEncryptBatchService encryptBatchService;

    /**
     * 分页获取批次
     */
    @PreAuthorize("@ss.hasPermi('encrypt:batch:list')")
    @GetMapping("/page")
    public TableDataInfo page(EncryptBatchEntity entity) {
        IPage<EncryptBatchEntity> pageList = encryptBatchService.selectEncryptBatchPage(plusPage(),entity);
        return getDataTable(pageList);
    }

    @PreAuthorize("@ss.hasPermi('encrypt:batch:list')")
    @GetMapping("/list")
    public AjaxResult list(EncryptBatchEntity entity) {
        return AjaxResult.success(encryptBatchService.selectEncryptBatchList(entity));
    }

    /**
     * 根据id获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('encrypt:batch:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable String id) {
        return success(encryptBatchService.getById(id));
    }

    /**
     * 新增权益活动
     */
    @PreAuthorize("@ss.hasPermi('encrypt:batch:add')")
    @Log(title = "券码分配", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody EncryptBatchEntity entity) {
        if(!encryptBatchService.checkBatchNameUnique(entity)) {
            return AjaxResult.error("新增批次名称 " + entity.getBatchName() + "已存在，请重新分配!");
        }

        if((entity.getTotalCoupons() <=0) || (entity.getTotalCoupons()>=10000)){
            return AjaxResult.error("分配数量为必须是【1--9999】之间");
        }

        entity.setId(SeqUtil.getSeqId());
        entity.setDelFlag("0");
        entity.setCreateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        entity.setCreateTime(new Date());

        return toAjax(encryptBatchService.addEncryptBatch(entity));
    }

    /**
     * 修改权益活动
     */
    @PreAuthorize("@ss.hasPermi('encrypt:batch:edit')")
    @Log(title = "券码分配", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody EncryptBatchEntity entity) {
        EncryptBatchEntity queryData = encryptBatchService.getById(entity.getId());
        if(queryData == null){
            return AjaxResult.error("批次信息不存在，无法修改!");
        }
        if(!encryptBatchService.checkBatchNameUnique(entity)){
            return AjaxResult.error("修改批次信息 "+entity.getBatchName()+"已存在，请重新分配!");
        }


        if(StringUtils.isNotEmpty(entity.getBatchName())){
            queryData.setBatchName(entity.getBatchName());
        }

        if(entity.getValidTime()!=null){
            queryData.setValidTime(entity.getValidTime());
        }
        if(entity.getStatus() != null){
            queryData.setStatus(entity.getStatus());
        }
        //只能修改批次名称、状态
        queryData.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserId()));
        queryData.setUpdateTime(new Date());
        return toAjax(encryptBatchService.updateById(queryData));
    }

    /**
     * 删除券码批次
     */
    @PreAuthorize("@ss.hasPermi('encrypt:batch:remove')")
    @Log(title = "券码分配", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids) {
        return toAjax(encryptBatchService.deleteBatchByIds(ids.toArray(new String[0])));
    }


    @PreAuthorize("@ss.hasPermi('encrypt:code:list')")
    @GetMapping("/codePage")
    public TableDataInfo page(EncryptCodePo entity) {
        if(StringUtils.isEmpty(entity.getBatchId())){
            throw new BaseException("批次号ID不能为空");
        }
        IPage<EncryptCodePo> pageList = encryptBatchService.selectEncrypCodePage(plusPage(),entity);
        return getDataTable(pageList);
    }

    @Log(title = "券码分配", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('encrypt:code:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, EncryptCodePo entity) {
        if(StringUtils.isEmpty(entity.getBatchId())){
            throw new BaseException("批次号ID不能为空");
        }
        List<EncryptCodePo> list = encryptBatchService.selectEncrypCodePage(entity);
        ExcelUtil<EncryptCodePo> util = new ExcelUtil<EncryptCodePo>(EncryptCodePo.class);
        util.exportExcel(response, list, "券码数据");
    }

}
